<!--组织树-->
<template>
  <div id="unitTree" class="flex-main">
    <!-- 左侧树展示 -->
    <div class="common-title">
      <h2>组织机构
        <el-tooltip class="item" effect="dark" content="刷新" placement="bottom">
          <i class="el-icon-refresh" @click="initOrgCategory" />
        </el-tooltip>
      </h2>
      <span v-if="organizationCategories.length>1" class="options">
        <el-dropdown class="tr color-primary" style="margin-top: 10px;cursor: pointer;font-weight: bold;" size="medium">
          <span class="el-dropdown-link">
            {{ currentSelectCategory.dataDictItemName }}<i class="el-icon-arrow-down el-icon--right" />
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="item in organizationCategories"
              :key="item.dataDictItemCode"
              :class="currentSelectCategory.id===item.id?'color-primary':''"
              @click.native="changeOrganizationCategory(item)">
              {{ item.dataDictItemName }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </span>
    </div>

    <el-input v-model="searchValue" placeholder="请输入组织名称" style="margin: 10px 0;" />
    <el-tree
      ref="tree"
      v-loading="treeLoading"
      class="common-el-tree tree-active"
      :data="treeDatas"
      :props="defaultTreeProps"
      node-key="id"
      default-expand-all
      :highlight-current="true"
      :filter-node-method="onTreeFilter"
      :expand-on-click-node="false"
      :current-node-key="selectedDataId"
      @node-click="handleNodeClick">
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <i v-if="data.type===1" class="el-icon-office-building" />
        <i v-else class="el-icon-price-tag" />
        <span v-if="data.type===1" class="text" style="font-weight:bold;font-size: 14px;">{{ node.data.organizationName }}({{ node.data.sortOrders }})</span>
        <span v-else class="text">{{ node.data.organizationName }}({{ node.data.sortOrders }})</span>
      </span>
    </el-tree>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.unitRecordShow" :title="sideBox.title" :width="'700px'" @close="sideBox.unitRecordShow =!sideBox.unitRecordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="organizationUnitRules"
          :model="organizationUnitRecord"
          label-position="right"
          label-width="150px">
          <el-form-item label="企业logo:" prop="logo">
            <single-image-upload
              ref="logo"
              v-model="organizationUnitRecord.logo"
              :catalog="constants.FILE_CATALOG_UNIT_LOGO" />
          </el-form-item>
          <el-form-item label="名称:" prop="organizationName">
            <el-input v-model="organizationUnitRecord.organizationName" maxlength="20" show-word-limit placeholder="请输入单位全称" />
          </el-form-item>
          <el-form-item label="单位编码:" prop="organizationCode">
            <el-input v-model="organizationUnitRecord.organizationCode" disabled maxlength="12" minlength="6" show-word-limit placeholder="请输入单位编码" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单位类型:" prop="organizationCategory">
                <data-dict-select v-model="organizationUnitRecord.organizationCategory" disabled :code="'organizationCategory'" placeholder="请选择单位类型" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属上级:" prop="pid">
                <el-select v-model="organizationUnitRecord.pid" placeholder="请选择所属单位" style="width:100%">
                  <el-option
                    v-for="item in parentOrgs"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="排序:" prop="sortOrders">
            <template slot="label">
              排序
              <el-tooltip class="item" effect="dark" content="值越大越靠前" placement="bottom">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-input-number v-model="organizationUnitRecord.sortOrders" placeholder="请输入排序" show-word-limit :max="9999" style="width:100%" />
          </el-form-item>
          <el-form-item label="统一社会信用代码:" prop="socialCreditCode">
            <el-input v-model="organizationUnitRecord.socialCreditCode" maxlength="18" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="营业执照:" prop="businessLicense">
            <single-image-upload
              ref="logo"
              v-model="organizationUnitRecord.businessLicense"
              :crop-ratio="210/297"
              :catalog="constants.FILE_CATALOG_UNIT_LICENSE" />
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item label="单位级别:" prop="organizationLevel">
                <data-dict-select v-model="organizationUnitRecord.organizationLevel" :disabled="sideBox.status==='update'" :code="'organizationLevel'" placeholder="请选择单位级别" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位标签:" prop="organizationTags">
                <data-dict-select v-model="organizationUnitRecord.organizationTags" multiple :code="'organizationTag'" placeholder="请选择单位标签" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="grid-content bg-purple">
                <el-form-item label="单位地址:" prop="regionLevel">
                  <region-selector ref="regionSelect" v-model="organizationUnitRecord.regionLevel" />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="详细地址:" prop="address">
                <el-input v-model="organizationUnitRecord.address" placeholder="请输入详细地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="经纬度:" prop="latlng">
            <map-point-selector v-model="organizationUnitRecord.latlng" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="电话:" prop="phone">
                <el-input v-model="organizationUnitRecord.phone" placeholder="请输入单位电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真:" prop="fax">
                <el-input v-model="organizationUnitRecord.fax" placeholder="请输入单位传真" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人:" prop="linkPerson">
                <el-input v-model="organizationUnitRecord.linkPerson" maxlength="5" show-word-limit placeholder="请输入单位联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话:" prop="linkMobile">
                <el-input v-model="organizationUnitRecord.linkMobile" maxlength="11" show-word-limit placeholder="请输入单位联系人电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="负责人:">
            <user-list-selector
              v-model="organizationUnitRecord.chargeInfo"
              mode="input"
              :org-id="organizationUnitRecord.id" />
          </el-form-item>
          <el-form-item label="工作时间:" prop="workTime">
            <el-input v-model="organizationUnitRecord.workTime" maxlength="50" show-word-limit placeholder="请输入单位工作时间" />
          </el-form-item>
          <el-row>
            <el-col :span="24">
              <el-form-item label="单位介绍:" prop="description">
                <el-input
                  v-model="organizationUnitRecord.description"
                  :rows="4"
                  type="textarea"
                  maxlength="200"
                  show-word-limit
                  placeholder="请输入单位介绍(限200字以内)" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createUnitData():updateUnitData()"> 保存</el-button>
      </template>
    </side-box>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.deptRecordShow" :title="sideBox.deptTitle" @close="sideBox.deptRecordShow =!sideBox.deptRecordShow">
      <template slot="body">
        <el-form
          ref="dataDeptForm"
          :rules="organizationDeptRules"
          :model="organizationDeptRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="名称:" prop="organizationName">
            <el-input v-model="organizationDeptRecord.organizationName" maxlength="20" show-word-limit placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="部门编码:" prop="organizationCode">
            <el-input v-model="organizationDeptRecord.organizationCode" disabled maxlength="12" minlength="6" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="所属上级:" prop="pid">
            <el-select v-model="organizationDeptRecord.pid" placeholder="请选择所属上级" style="width:100%">
              <el-option
                v-for="item in parentOrgs"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="排序:" prop="sortOrders">
            <template slot="label">
              排序
              <el-tooltip class="item" effect="dark" content="值越大越靠前" placement="bottom">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-input-number v-model="organizationDeptRecord.sortOrders" placeholder="请输入排序" show-word-limit :max="9999" style="width:100%" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="电话:" prop="phone">
                <el-input v-model="organizationDeptRecord.phone" placeholder="请输入单位电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真:" prop="fax">
                <el-input v-model="organizationDeptRecord.fax" placeholder="请输入单位传真" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人:" prop="linkPerson">
                <el-input v-model="organizationDeptRecord.linkPerson" maxlength="5" show-word-limit placeholder="请输入单位联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话:" prop="linkMobile">
                <el-input v-model="organizationDeptRecord.linkMobile" maxlength="11" show-word-limit placeholder="请输入单位联系人电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="负责人:">
            <user-list-selector
              v-model="organizationDeptRecord.chargeInfo"
              mode="input"
              :org-id="organizationDeptRecord.id" />
          </el-form-item>
          <el-row>
            <el-col :span="24">
              <el-form-item label="部门介绍:" prop="description">
                <el-input
                  v-model="organizationDeptRecord.description"
                  :rows="4"
                  type="textarea"
                  maxlength="200"
                  show-word-limit
                  placeholder="请输入部门介绍(限200字以内)" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template slot="foot">
        <el-button plain type="primary" @click="sideBox.status==='create'?createDeptData():updateDeptData()">保存</el-button>
      </template>
    </side-box>
    <model-dialog title="组织机构调整" :visible="adjustmentOrgDialog" width="600px" @close="adjustmentOrgDialog=!adjustmentOrgDialog">
      <template>
        <el-form :model="adjustmentOrgRecord" label-position="right" label-width="120px">
          <el-form-item label="当前组织:">
            <el-input v-model="adjustmentOrgRecord.currentOrg" disabled />
          </el-form-item>
          <el-form-item label="调整至:">
            <el-select-tree
              v-model="adjustmentOrgRecord.targetOrg"
              :data="targetOrgTreeDatas"
              :props="{ children: 'children', label: 'organizationName'}"
              @selected="selectedTargetOrgInfo" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="footer">
        <el-button type="primary" @click="confirmAdjustmentOrg">调 整</el-button>
      </template>
    </model-dialog>
  </div>
</template>
<script>
export default {
  components: { },
  props: {
    isExpandAll: { type: Boolean, default: true } // 是否展开所有节点
  },
  data() {
    return {
      defaultTreeProps: {
        children: 'children',
        label: 'organizationName'
      },
      expandRowKeys: [],

      organizationCategories: [],
      currentSelectCategory: {},
      searchValue: '',
      treeDatas: [],
      expandTreeDatas: [],
      treeLoading: false,
      selectedDataId: '',
      selectedTreeData: {},
      selectedTreeNode: {},
      currentSelectedOrg: {},
      // 固定写法
      sideBox: {
        unitRecordShow: false,
        title: '',
        deptRecordShow: false,
        deptTitle: '',
        status: 'create' // 对话框状态
      },
      parentOrgs: [],
      organizationUnitRecord: {
      },
      organizationUnitRules: {
        /* socialCreditCode: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
          { min: 18, max: 18, message: '请输入18位长度的统一社会信用代码', trigger: 'blur' }
        ],*/
        organizationName: [
          { required: true, message: '请输入单位名称', trigger: 'blur' }
        ],
        organizationCategory: [
          { required: true, message: '请选择单位类型', trigger: 'blur' }
        ],
        organizationCode: [
          { required: true, message: '请输入单位编号', trigger: 'blur' }
        ],
        pid: [
          { required: true, message: '请选择所属单位', trigger: 'blur' }
        ],
        sortOrders: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]

      },
      organizationDeptRecord: {

      },
      organizationDeptRules: {
        organizationName: [
          { required: true, message: '请输入全称', trigger: 'blur' }
        ],
        organizationCode: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        pid: [
          { required: true, message: '请选择所属部门', trigger: 'blur' }
        ],
        sortOrders: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      },
      targetOrgTreeDatas: [],
      adjustmentOrgDialog: false,
      adjustmentOrgRecord: {}
    }
  },
  watch: {
    searchValue(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {},
  created() {
    this.initOrgCategory()
  },
  methods: {
    initOrgCategory() {
      this.$store.dispatch('findDataDictItemByCode', 'organizationCategory').then((res) => {
        this.organizationCategories = res
        if (res.length > 0) {
          this.currentSelectCategory = res[0]
          this.loadOrganizationTree()
        }
      }).catch((_) => {

      })
    },
    changeOrganizationCategory(item) {
      this.currentSelectCategory = item
      this.loadOrganizationTree()
    },
    async loadOrganizationTree() {
      this.treeDatas.length = 0
      this.treeLoading = true
      const response = await this.$store.dispatch('loadOrganizationTree', {
        pid: 0,
        category: this.currentSelectCategory.dataDictItemCode
      })

      this.treeDatas = (response)
      if (response.length > 0) {
        this.$nextTick(() => {
          this.handleNodeClick(response[0], this.$refs.tree.getNode(response[0].id))
        })
      } else {
        this.currentSelectedOrg = {}
        this.$emit('selectedOrg', {})
        this.selectedTreeNode = null
        this.selectedTreeData = null
      }

      this.treeLoading = false
    },
    async loadNextData(node, resolve) {
      var temp = this.expandTreeDatas.filter((item) => {
        return item.id === node.data.id
      })
      if (temp.length > 0) {
        resolve(temp[0].children)
      } else {
        if (node.data.id) {
          const response = await this.$store.dispatch('loadOrganization', { pid: node.data.id })
          var temps = []
          response.forEach((item) => {
            item.isParent = true
            item.hasChildren = true
            item.ext = item.type + ':'
            item.label = item.fullName
            item.leaf = true
            temps.push(item)
          })
          resolve(temps)
        }
      }
    },
    handleNodeClick(data, node) {
      this.selectedTreeNode = node
      this.selectedTreeData = data
      this.selectedDataId = data.id
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(data.id)
      })
      this.getOrgInfo(data.id)
      this.$refs.tree.setCheckedKeys([data.id])
    },
    getParentIds(node) {
      if (!node.parent) {
        return
      }
      var parentData = node.parent.data
      if (parentData instanceof Array) {
        return
      }
      /* if (parentData.ext === '1:') {
        this.fullPathId.push(parentData.id)
        this.fullPathName.push(parentData.label)
      } else {
        this.fullPathId.push(parentData.id)
        this.fullPathName.push(parentData.label)
        this.getParentIds(node.parent)
      }*/
      this.fullPathId.push(parentData.id)
      this.fullPathName.push(parentData.label)
      this.getParentIds(node.parent)
    },
    /* 节点过滤函数 */
    onTreeFilter(value, data) {
      if (!value) return true
      return data[this.defaultTreeProps.filter] ? data[this.defaultTreeProps.label].indexOf(value) !== -1 || data[this.defaultTreeProps.filter].indexOf(value.toUpperCase()) !== -1 : data[this.defaultTreeProps.label].indexOf(value) !== -1
    },

    // 新增机构
    async handleCreateUnitConfirm() {
      this.parentOrgs = []
      var { id, organizationName } = this.currentSelectedOrg
      if (id) {
        this.$confirm('请选择新建机构所属上级?', '提示', {
          confirmButtonText: `本级【${organizationName}】`,
          cancelButtonText: '根目录',
          type: 'warning'
        }).then(() => {
          this.parentOrgs.push({
            label: organizationName,
            value: id
          })
          this.handleCreateUnit(id)
        }).catch(() => {
          id = '0'
          this.parentOrgs.push({
            label: '根目录',
            value: '0'
          })
          this.handleCreateUnit(id)
        })
      } else {
        id = '0'
        this.parentOrgs.push({
          label: '根目录',
          value: '0'
        })
        this.handleCreateUnit(id)
      }
    },
    async handleCreateUnit(pid) {
      this.sideBox = {
        status: 'create',
        unitRecordShow: true,
        title: '新增单位'
      }
      var orgCodeResult = await this.$store.dispatch('generateOrganizationCode', { type: 1, pid: pid })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.organizationUnitRecord = {
          organizationCategory: this.currentSelectCategory.dataDictItemCode,
          pid: pid,
          organizationCode: orgCodeResult,
          regionLevel: [],
          organizationTags: [],
          sortOrders: 9999
        }
      })
    },
    // 新增部门
    async handleCreateDept() {
      this.parentOrgs = []
      var { id, organizationName, organizationCategory } = this.currentSelectedOrg
      this.parentOrgs.push({
        label: organizationName,
        value: id
      })
      var orgCodeResult = await this.$store.dispatch('generateOrganizationCode', { type: 2, pid: id })
      this.organizationDeptRecord = {
        organizationCode: orgCodeResult,
        pid: id,
        organizationCategory: organizationCategory,
        organizationName: '',
        sortOrders: 9999

      }
      this.sideBox = {
        status: 'create',
        deptRecordShow: true,
        deptTitle: `新增【${organizationName}】下级部门`
      }
      this.$nextTick(() => {
        this.$refs['dataDeptForm'].clearValidate()
      })
    },
    createUnitData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          var tempData = Object.assign({}, this.organizationUnitRecord)
          tempData = {
            ...tempData,
            regionLevel1: tempData.regionLevel[0],
            regionLevel2: tempData.regionLevel[1],
            regionLevel3: tempData.regionLevel[2],
            regionLevel4: tempData.regionLevel[3],
            organizationTag: tempData.organizationTags ? tempData.organizationTags.join(',') : null
          }
          delete tempData.children
          delete tempData.regionLevel
          delete tempData.organizationTags
          delete tempData._organizationTags
          delete tempData._fullOrgIds
          delete tempData._fullOrgNames
          this.$store.dispatch('upmsOrganizationUnitSave', tempData).then(response => {
            this.sideBox.unitRecordShow = false
            this.$modal.msgSuccess('创建成功')
            this.loadOrganizationTree()
          }).catch(() => {
            this.sideBox.unitRecordShow = true
          })
        }
      })
    },

    createDeptData() {
      this.$refs['dataDeptForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('upmsOrganizationDeptSave', this.organizationDeptRecord).then(response => {
            this.sideBox.deptRecordShow = false
            this.$modal.msgSuccess('创建成功')
            this.loadOrganizationTree()
          }).catch(() => {
            this.sideBox.deptRecordShow = true
          })
        }
      })
    },

    async handleUpdate() {
      this.organizationUnitRecord = Object.assign({}, this.currentSelectedOrg)
      this.organizationUnitRecord = {
        ...this.organizationUnitRecord,
        organizationTags: this.organizationUnitRecord.organizationTag ? this.organizationUnitRecord.organizationTag.split(',') : [],
        regionLevel: [this.organizationUnitRecord.regionLevel1, this.organizationUnitRecord.regionLevel2, this.organizationUnitRecord.regionLevel3, this.organizationUnitRecord.regionLevel4]
      }
      this.parentOrgs = []

      if (this.organizationUnitRecord.type === 1) {
        this.parentOrgs.push({
          label: '根目录',
          value: '0'
        })
        this.sideBox = {
          status: 'update',
          unitRecordShow: true,
          title: `编辑[${this.organizationUnitRecord.organizationName}]`
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
      if (this.organizationUnitRecord.pid !== '0') {
        var parentOrg = await this.$store.dispatch('upmsOrganizationGetDetailsById', this.organizationUnitRecord.pid)
        if (parentOrg) {
          this.parentOrgs.push({
            label: parentOrg.organizationName,
            value: parentOrg.id
          })
        }
      }

      if (this.organizationUnitRecord.type === 2) {
        this.organizationDeptRecord = Object.assign({}, this.currentSelectedOrg) // copy obj
        this.sideBox = {
          status: 'update',
          deptRecordShow: true,
          deptTitle: `编辑【${this.organizationUnitRecord.organizationName}】`
        }
        this.$nextTick(() => {
          this.$refs['dataDeptForm'].clearValidate()
        })
      }
    },
    updateUnitData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          var tempData = Object.assign({}, this.organizationUnitRecord)
          tempData = {
            ...tempData,
            regionLevel1: tempData.regionLevel[0],
            regionLevel2: tempData.regionLevel[1],
            regionLevel3: tempData.regionLevel[2],
            regionLevel4: tempData.regionLevel[3],
            organizationTag: tempData.organizationTags ? tempData.organizationTags.join(',') : null
          }
          delete tempData.children
          delete tempData.regionLevel
          delete tempData.organizationTags
          delete tempData._organizationTags
          delete tempData._fullOrgIds
          delete tempData._fullOrgNames
          this.$store.dispatch('upmsOrganizationUnitUpdate', tempData).then(response => {
            this.sideBox.unitRecordShow = false
            this.$modal.msgSuccess('修改成功')
            this.loadOrganizationTree()
            this.getOrgInfo(this.organizationUnitRecord.id)
          }).catch(() => {
            this.sideBox.unitRecordShow = true
          })
        }
      })
    },
    handleInvitationCode() {
      this.$store.dispatch('upmsOrganizationInvitationCode', this.currentSelectedOrg.id).then(response => {
        this.$modal.msgSuccess('邀请码生成成功')
        this.getOrgInfo(this.currentSelectedOrg.id)
      }).catch(() => {
      })
    },
    updateDeptData() {
      this.$refs['dataDeptForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.organizationDeptRecord)
          tempData.children = null
          delete tempData._fullOrgIds
          delete tempData._fullOrgNames
          delete tempData._organizationTags
          delete tempData._organizationTags
          this.$store.dispatch('upmsOrganizationDeptUpdate', tempData).then(response => {
            this.sideBox.deptRecordShow = false
            this.$modal.msgSuccess('修改成功')
            this.loadOrganizationTree()
            this.getOrgInfo(this.organizationDeptRecord.id)
          }).catch(() => {
            this.sideBox.deptRecordShow = true
          })
        }
      })
    },
    handleRemove() {
      if (this.currentSelectedOrg.isBuiltIn === 1) {
        this.$modal.msgWarning('内置数据,无权删除')
        return
      }
      if (this.selectedTreeNode.childNodes.length > 0) {
        this.$modal.msgWarning(`请先删除[${this.currentSelectedOrg.organizationName}]的子节点！`)
        return
      }
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('upmsOrganizationRemove', [this.currentSelectedOrg.id]).then(response => {
          this.$modal.msgSuccess('删除成功')
          const parent = this.selectedTreeNode.parent
          const children = parent.data.children || parent.data
          const index = children.findIndex(d => d.id === this.selectedTreeData.id)
          children.splice(index, 1)
          if (parent.level === 0) {
            this.loadOrganizationTree()
          } else {
            this.$refs.tree.setCheckedKeys([parent.data.id])
            this.getOrgInfo(parent.data.id)
          }
        }).catch(() => {})
      }).catch(() => {})
    },
    handleDissolution() {
      this.$confirm(`您确定要解散企业【${this.currentSelectedOrg.organizationName}】,解散后，该企业的后台管理账号和通讯录将会删除,该操作不可撤销，请谨慎操作， 是否继续?`, '系统提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        this.$store.dispatch('upmsOrganizationDissolution', this.currentSelectedOrg.id).then((res) => {
          this.$modal.msgSuccess('企业解散成功！')
          this.loadOrganizationTree()
        })
      }).catch(() => {
      })
    },
    getOrgInfo(id) {
      this.$store.dispatch('upmsOrganizationGetDetailsById', id).then((res) => {
        this.currentSelectedOrg = res || {}
        this.$emit('selectedOrg', this.currentSelectedOrg)
      })
    },
    handleAdjust() {
      this.adjustmentOrgRecord = {
        id: this.currentSelectedOrg.id,
        currentOrg: this.currentSelectedOrg.organizationName,
        targetOrg: null
      }
      this.adjustmentOrgDialog = true
      this.targetOrgTreeDatas = Object.assign([], this.treeDatas)
    },
    selectedTargetOrgInfo(data) {
      if (data.fullPathId.indexOf(this.currentSelectedOrg.id) > -1) {
        this.$modal.msgWarning('当前组织已经在目标组织，无法调整!')
        this.adjustmentOrgRecord = {
          ...this.adjustmentOrgRecord,
          targetOrg: ''
        }
        return
      }
    },
    confirmAdjustmentOrg() {
      if (!this.adjustmentOrgRecord.targetOrg) {
        this.$modal.msgWarning('请选择目标组织')
        return
      }
      this.$store.dispatch('organizationAdjustment', this.adjustmentOrgRecord).then((res) => {
        this.loadOrganizationTree()
        this.$modal.msgSuccess('调整成功！')
        this.adjustmentOrgDialog = false
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" >
</style>
